import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getuserCode, setuserCode, removeuserCode } from '@/utils/userCode'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return{
    token: getToken(),
    name: '',
    userCode: getuserCode(),
    avatar: '',
    rolearray: [],
  }
}
const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLEARRAY: (state, rolearray) => {
    state.rolearray = rolearray
  },
  SET_USERCODE: (state, userCode) => {
    state.userCode = userCode
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { userCode, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userCode: userCode.trim(), password: password }).then(res => {
        commit('SET_TOKEN', res.responseBody)
        commit('SET_USERCODE', userCode.trim())
        setToken(res.responseBody)
        setuserCode(userCode.trim())
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo({ userCode: state.userCode }).then(response => {
        const { responseBody } = response
        if (response.retCode !== '200') {
          reject('认证失败，请重新登入！')
        }
        const { userName, aRoleAuthDTO, userCode } = responseBody
        commit('SET_NAME', userName)
        commit('SET_AVATAR', '')
        commit('SET_ROLEARRAY', aRoleAuthDTO)
        commit('SET_USERCODE', userCode)
        commit('SET_USERCODE', userCode)
        resolve(responseBody)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      removeToken()
      removeuserCode()
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  },

  // setToken
  setToken({ commit }, token) {
    commit('SET_TOKEN', token)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
